package com.maosy.demo.webview

import android.annotation.SuppressLint
import android.util.Log
import android.view.KeyEvent
import android.webkit.WebView
//import jp.hituzi.kamome.Client
//import jp.hituzi.kamome.Command

@SuppressLint("StaticFieldLeak")
object WebViewUtil {

//    private lateinit var client: Client

    @SuppressLint("SetJavaScriptEnabled")
    fun init(webView: WebView) {
        webView.settings.javaScriptEnabled = true
//        webView.webViewClient = WebViewClient()
//        client = Client(webView)
//        // 注册 JSBridge 方法
//        addEcho(client)
    }

    /**
     * 关闭webview清理页面堆栈和缓存
     */
    fun clearHis(webView: WebView) {
        webView.settings.javaScriptEnabled = false
        webView.clearHistory()
        webView.clearCache(true)
    }

    fun setBackListener(webView: WebView) {
        webView.setOnKeyListener { view, code, keyEvent ->
            Log.i(this::class.simpleName, "view:$view,code:$code,keyEvent:$keyEvent")
            if (code == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                webView.goBack()
                return@setOnKeyListener true
            }
            false
        }
    }
}

//private fun addEcho(client: Client) {
//    // Registers `echo` command.
//    client.add(Command("echo") { commandName, data, completion ->
//        // Received `echo` command.
//        // Then sends resolved result to the JavaScript callback function.
//        val map = HashMap<String?, Any?>()
//        map["message"] = data!!.optString("message")
//        completion.resolve(map)
//        // Or, sends rejected result if failed.
//        //completion.reject("Echo Error!")
//    })
//}